package com.xtravel.common.helper;

import android.util.Log;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.util.Map;

public class HttpHelper {
	private static final String BASE_URL = "http://121.41.88.34/api/app/";

	public static String httpGet(String api, Map<String, String> args) {
		try {
			String url = BASE_URL + api;
			String serverUrl = createUrl(url, args);
			HttpGet request = new HttpGet(serverUrl);
			if (UserContext.IsSignin()) {
				request.setHeader("token", UserContext.GetCurrentToken().getToken());
			}

			HttpResponse response = new DefaultHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(response.getEntity());
			}

			return null;
		} catch (Exception e) {
			return null;
		}
	}

	public static String post(String api, Map<String, String> args){
		try {
			String url = BASE_URL + api;
			HttpPost request = new HttpPost(url);
			if (UserContext.IsSignin()) {
				request.setHeader("token", UserContext.GetCurrentToken().getToken());
			}

			Gson gson = new Gson();
			StringEntity jsonEntity = new StringEntity(gson.toJson(args), HTTP.UTF_8);
			jsonEntity.setContentType("application/json");
			request.setEntity(jsonEntity);

			HttpResponse response = new DefaultHttpClient().execute(request);
			if (response.getStatusLine().getStatusCode() < 500) {
				return EntityUtils.toString(response.getEntity());
			} else {
				Log.d("HttpHelper", String.format("response code:%s", response.getStatusLine().getStatusCode()));
			}

			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	private static String createUrl(String url, Map<String, String> args) {
		if (args == null) {
			return url;
		}

		url += "?";
		for (String key : args.keySet()) {
			url += key + "=" + args.get(key) + "&";
		}

		return url;
	}
}
